# Create your views here.
import os
from alipay import AliPay
from django import http
from django.conf import settings
from django.shortcuts import render
from django.views import View
from meiduo_mall.utils.response_code import RETCODE
from meiduo_mall.utils.views import LoginRequiredJSONMixin
from orders.models import OrderInfo
from .models import Payment
# 支付宝沙箱环境的测试账号: idqcvi3338@sandbox.com
class PaymentStatusView(View):
    """保存订单支付结果"""
    def get(self, request):
        # 获取所有的查询字符串参数
        query_dict = request.GET
        # 将查询字符串参数的类型转换成标准的字典类型
        data=query_dict.dict()
        # 从查询字符串对应的字典类型中获取并移除sign数据，不能参与签名验证
        signature=data.pop("sign")
        print("data=",data)
        print("signature=",signature)
        # 创建SDK对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=open(
                os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem")).read(),
            alipay_public_key_string=open(
                os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/alipay_public_key.pem")).read(),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        # 使用SDK对象，调用验证通知接口函数，得到验证结果
        success=alipay.verify(data,signature)
        # 如验证通过，需要将支付宝的支付状态进行处理(将美多商场的订单id和支付宝的订单id进行绑定，修改订单状态)
        if success:
            # 得到美多商城维护的订单ID
            order_id = data.get("out_trade_no")
            # 得到支付宝维护的订单id
            trade_id = data.get("trade_no")
            Payment.objects.create(order_id=order_id,trade_id=trade_id)
            # 修改订单状态由"待支付"改成"待评价"
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(
                status=OrderInfo.ORDER_STATUS_ENUM["UNCOMMENT"])
            # 响应结果
            context={
                "trade_id":trade_id
            }
            return render(request,"pay_success.html",context)
        else:
            return http.HttpResponseForbidden("非法请求")

class PaymentView(LoginRequiredJSONMixin, View):
    """订单支付功能"""
    def get(self,request, order_id):
        """
        :param request:
        :param order_id: 当前要支付的订单id
        :return: JSON
        """
        # 查询要支付的订单
        user = request.user
        try:
            order = OrderInfo.objects.get(order_id=order_id, user=user, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return http.HttpResponseForbidden('订单信息错误')

        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem")).read(),
            alipay_public_key_string=open(os.path.join(os.path.dirname(os.path.abspath(__file__)),"keys/alipay_public_key.pem")).read(),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        # 生成登录支付宝连接
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject="美多商城%s" % order_id,
            return_url=settings.ALIPAY_RETURN_URL,
        )

        # 响应登录支付宝连接
        # 真实环境电脑网站支付网关：https://openapi.alipay.com/gateway.do? + order_string
        # 沙箱环境电脑网站支付网关：https://openapi.alipaydev.com/gateway.do? + order_string
        alipay_url = settings.ALIPAY_URL + "?" + order_string
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'alipay_url': alipay_url})